import $ from "jquery";

export default {
  state:{
    id: "",
    username:"",
    email:"",
    tel:"",
    sexType:null,
    schoolCode:null,
    userAlias:"",
    is_login:false,
    token:""
  },
  getters:{},
  mutations:{
    updateUser(state,user){
      state.id = user.id;
      state.username = user.username;
      state.email = user.email;
      state.tel = user.tel;
      state.sexType = user.sexType;
      state.schoolCode = user.schoolCode;
      state.userAlias = user.userAlias;
      state.is_login = true;
    },
    updateToken(state,token){
      state.token = token;
    }
  },
  actions:{
    login(context,data){
      $.ajax({
        url:"http://127.0.0.1:8081/user/account/token/",
        type:"post",
        data:{
          username:data.username,
          password:data.password
        },
        success(resp){
          if(resp.error_message == "success") {
            context.commit("updateToken", resp.token);
            data.success(resp);
          }else{
            data.error(resp);
          }
        },
        error(resp) {
          data.error(resp);
        }});
    },
    getinfo(context,data){
      $.ajax({
        url:"/api/user/account/info/",
        type:"get",
        headers:{
          Authorization: "Bearer " + context.state.token,
        },
        success(resp){
          if(resp.error_message == "success") {
            context.commit("updateUser", {
              ...resp,
              is_login: true
            });
            data.success(resp);
          }else {
            data.error(resp);
          }
        },
        error(resp) {
          data.error(resp)
        }})
    }

  },
  modules:{}

}
